import {Types} from "mongoose";
import {KickbackRecordModel} from "../../../database/models/kickbackRecord";
import {PaymentOrderModel} from "../../../database/models/paymentOrder";
import {RechargeOrderModel} from "../../../database/models/rechargeOrder";
import {searchAry} from "../../../utils/search";

export const typeDefs = `
type RechargeOrder{
  _id:String!
  player: Player
  RMBCost: Float!
  coin: Int!
  freeCoin: Int!
  gem: Int!
  createAt: String!
  inviteBy: GM,
  state: String!
  kick: Kickback
  payOrder: PayOrder!
  finishAt: String
  payOrder: PayOrder!
}

type Kickback{
  level2: GM
  kickback2: Float
  level1: GM
  kickback1: Float
  kickbackAll: Float!
}
type PayOrder{
_id: String!
orderType: String!
state: String
price: Float!
createAt: String!
paymentType: String!
}
`

export const queryDefs = `
  getRechargeOrders(page: Int, size: Int, searchText: String):[RechargeOrder]!
`

export const mutationDefs = ``

export const resolvers = {
  Query: {
    getRechargeOrders: async (_, {page = 0, size = 20, searchText}, context) => {
      const authedUser = context.request.user

      if (!authedUser)
        throw Error(`unavailable`)

      const query = authedUser.role === `super` ? {} : {inviteBy: authedUser._id}

      // const from = moment().subtract(365, 'day').toDate()
      let orders = null
      if (searchText)
        orders = await RechargeOrderModel.find({state: `paid`, ...query})
          .populate(`player`)
          .sort({createAt: -1}).lean()
      else
        orders = await RechargeOrderModel.find({state: `paid`, ...query})
          .populate(`player`)
          .skip(page * size).limit(size)
          .sort({createAt: -1}).lean()

      for (const it of orders) {
        it.Str = it._id.toString()
        const kick = await KickbackRecordModel.findOne({fromId: Types.ObjectId(it._id)})
          .populate(`level2`)
          .populate(`level1`)
          .lean()

        if (kick) {
          it.kickStr = kick._id.toString()
          it.kick = kick
        }
        const payOrder = await PaymentOrderModel.findOne({order: it._id.toString()}).lean()
        it.payOrder = payOrder
        it.payOrderStr = payOrder._id.toString()
      }

      const reg = new RegExp(searchText, `i`)
      let rlt = searchAry(orders, reg)
      if (searchText)
        rlt = rlt.slice(page * size, (page + 1) * size)
      return rlt
    },
  },
  Mutation: {}
}
